package com.yonyou.openapi.service;

import com.github.benmanes.caffeine.cache.Cache;
import com.yonyou.openapi.base.auth.token.OpenApiTokenCacheProvider;
import com.yonyou.openapi.base.datacenter.impl.DataCenterUrlProviderImpl;
import com.yonyou.openapi.base.datacenter.pojo.GatewayAddressResponse;
import com.yonyou.openapi.base.response.OpenApiAccessToken;
import com.yonyou.openapi.configure.ApiBaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.Objects;


@Slf4j
public class TokenProviderImpl extends DataCenterUrlProviderImpl implements OpenApiTokenCacheProvider {

    @Resource
    Cache<String,GatewayAddressResponse.GatewayAddressDTO> moreDataUrlCache;
    @Resource
    Cache<String, OpenApiAccessToken> tokenCache;


    /**
     * TODO：不建议每次都调用接口，建议将租户地址对应关系持久化到数据库或者缓存中
     * @return GatewayAddressResponse.GatewayAddressDTO
     */
    @Override
    public GatewayAddressResponse.GatewayAddressDTO queryGatewayAddress() {
        GatewayAddressResponse.GatewayAddressDTO gatewayAddressDTO = Objects.requireNonNull(moreDataUrlCache).asMap().get("moreDataUrl");
        if(gatewayAddressDTO==null){
            GatewayAddressResponse.GatewayAddressDTO queryGatewayAddress = super.queryGatewayAddress();
            gatewayAddressDTO = queryGatewayAddress;
            moreDataUrlCache.put("moreDataUrl",queryGatewayAddress);
        }
        return gatewayAddressDTO;
    }

    /**
     *  TODO: 从缓存中获取token
     * @return token对象  返回null说明过期，会重新走获取token的逻辑
     */
    @Override
    public OpenApiAccessToken loadTokenFromCache() {
        OpenApiAccessToken openApiAccessToken = Objects.requireNonNull(tokenCache).asMap().get("tokenCache");
        if(openApiAccessToken!=null){
            //判断有效期,如果大于30分钟则返回token
            long currentTime = System.currentTimeMillis();
            if(openApiAccessToken.getExpiredAt()-currentTime>30*60*1000){
                return openApiAccessToken;
            }
        }
        return null;
    }

    /**
     *  TODO：建议对token进行缓存处理
     * @param token token实体
     */
    @Override
    public void saveTokenToCache(OpenApiAccessToken token) {
        tokenCache.put("tokenCache",token);
    }

}
